<?php

declare(strict_types=1);

namespace app\controller\admin;

use app\model\admin\Areas;
use app\model\admin\CateModel;
use app\model\admin\Pact;
use app\model\admin\ShippingTemp;
use app\model\admin\ShippingTempFree;
use app\model\admin\ShippingTempNoDe;
use app\model\admin\ShippingTempRegion;
use Error;
use think\facade\Db;
use think\facade\Validate;
use think\Request;

class ShippingTempController extends AdminBaseController
{
    // 获取列表
    public function index(Request $request)
    {
        $params = $request->param(['name', 'status', 'created_at']);
        $list = ShippingTemp::scope('where', $params)->order('id', 'desc')->paginate([
            'list_rows' => $this->limit,
            'page' => $this->page,
            'var_page' => $this->pageVar
        ]);
        return successPage($list);
    }
    public function getAll(Request $request)
    {
        // $params = $request->param(['name', 'status', 'created_at']);
        $list = ShippingTemp::select();
        return success($list);
    }

    // 添加
    public function create(Request $request)
    {
        $validate = Validate::rule([
            "name" => "require",
            "sort" => "require",
            "status" => "require",
            "send_type" => "require", //配送：1全国2指定
            "appoint" => "require", //1指定包邮2不指定包邮
            "type" => "require",  //计费方式
            "no_delivery" => "require",  //指定不送达 1开启2关闭
        ]);
        $params = $request->param(['name', 'sort', 'status', 'send_type', 'appoint', 'type', 'no_delivery', 'send_area', 'free_area', 'no_delivery_data']);
        // 检验参数
        if (!$validate->check($params)) {
            return error($validate->getError());
        }
        try {
            $this->handleArea($params);
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
        return success();
    }

    // 修改
    public function update(Request $request, $id)
    {
        $validate = Validate::rule([
            "name" => "require",
            "sort" => "require",
            "status" => "require",
            "send_type" => "require", //配送：1全国2指定
            "appoint" => "require", //1指定包邮2不指定包邮
            "type" => "require",  //计费方式
            "no_delivery" => "require",  //指定不送达 1开启2关闭
        ]);
        $params = $request->param(['name', 'sort', 'status', 'send_type', 'appoint', 'type', 'no_delivery', 'send_area', 'free_area', 'no_delivery_data']);
        // 检验参数
        if (!$validate->check($params)) {
            return error($validate->getError());
        }
        $info = ShippingTemp::find($id);
        if (!$info) {
            return error('参数错误');
        }
        try {
            $this->handleArea($params, $info);
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
        return success();
    }
    // 获取详情
    public function detail(Request $request, $id)
    {
        $info = ShippingTemp::with(['region', 'free', 'noDe'])->where('id', $id)->find();
        foreach ($info['region'] as $key => $val) {
            $val['province_id'] = explode(',', $val['province_id']);
            if ($val['city_id']) {
                $val['city_id'] = explode(',', $val['city_id']);
            }
            //设置citylist
            $val['cityList'] = Areas::whereIn('parent_id', $val['province_id'])->select();
        }
        foreach ($info['free'] as $key => $val) {
            $val['province_id'] = explode(',', $val['province_id']);
            if ($val['city_id']) {
                $val['city_id'] = explode(',', $val['city_id']);
            }
            //设置citylist
            $val['cityList'] = Areas::whereIn('parent_id', $val['province_id'])->select();
        }
        foreach ($info['noDe'] as $key => $val) {
            $val['province_id'] = explode(',', $val['province_id']);
            if ($val['city_id']) {
                $val['city_id'] = explode(',', $val['city_id']);
            }
            //设置citylist
            $val['cityList'] = Areas::whereIn('parent_id', $val['province_id'])->select();
        }
        return success($info);
    }
    public function del(Request $request, $id)
    {
        Db::transaction(function () use ($id) {
            ShippingTemp::destroy($id);
            ShippingTempRegion::where('temp_id', $id)->delete();
            ShippingTempFree::where('temp_id', $id)->delete();
            ShippingTempNoDe::where('temp_id', $id)->delete();
        });
        return success();
    }
    protected function handleArea($params, $info = null)
    {
        try {
            Db::transaction(function () use ($params, $info) {
                $temp_id = null;
                if ($info) {
                    $temp_id = $info->id;
                }
                if ($temp_id) {
                    ShippingTemp::update([
                        "name" => $params['name'],
                        "sort" => $params['sort'],
                        "status" => $params['status'],
                        "type" => $params['type'],
                        "appoint" => $params['appoint'],
                        "send_type" => $params['send_type'],
                        "no_delivery" => $params['no_delivery'],
                    ], ['id' => $temp_id]);
                    // 删除原先的
                    ShippingTempRegion::where('temp_id', $temp_id)->delete();
                    ShippingTempFree::where('temp_id', $temp_id)->delete();
                    ShippingTempNoDe::where('temp_id', $temp_id)->delete();
                } else {
                    $temp = ShippingTemp::create([
                        "name" => $params['name'],
                        "sort" => $params['sort'],
                        "status" => $params['status'],
                        "type" => $params['type'],
                        "appoint" => $params['appoint'],
                        "send_type" => $params['send_type'],
                        "no_delivery" => $params['no_delivery'],
                    ]);
                    $temp_id = $temp->id;
                }



                if ($params['send_type'] == 2) {
                    // 处理指定地区
                    // 指定地区配送
                    if (!is_array($params['send_area'])) {
                        throw new Error('请选择需要配送的指定区域');
                    }
                    foreach ($params['send_area'] as $key => $val) {
                        $province_id = $val['province_id'] ?? [];
                        $city_id = $val['city_id'] ?? [];
                        if ($city_id && count($city_id)) {
                            ShippingTempRegion::create([
                                "province_id" => implode(',', $province_id),
                                "city_id" => implode(',', $city_id),
                                "temp_id" => $temp_id,
                                "first" => $val['first'],
                                "first_price" => $val['first_price'],
                                "continue" => $val['continue'],
                                "continue_price" => $val['continue_price'],
                                "type" => $params['type'],
                            ]);
                        } else {
                            ShippingTempRegion::create([
                                "province_id" => implode(',', $province_id),
                                // "city_id" => implode(',', $city_id),
                                "temp_id" => $temp_id,
                                "first" => $val['first'],
                                "first_price" => $val['first_price'],
                                "continue" => $val['continue'],
                                "continue_price" => $val['continue_price'],
                                "type" => $params['type'],
                            ]);
                        }
                    }
                }
                // 处理包邮
                if ($params['appoint'] == 1) {
                    // 指定地区包邮
                    if (!is_array($params['free_area'])) {
                        throw new Error('请选择包邮的指定区域');
                    }
                    foreach ($params['free_area'] as $key => $val) {
                        $province_id = $val['province_id'] ?? [];
                        $city_id = $val['city_id'] ?? [];
                        if ($city_id && count($city_id)) {
                            ShippingTempFree::create([
                                "province_id" => implode(',', $province_id),
                                "temp_id" => $temp_id,
                                "city_id" => implode(',', $city_id),
                                "number" => $val['number'] ?? 0, //默认包邮单位为0 意味着不包邮
                                "price" => $val['price'] ?? 0, //默认包邮价格为0 意味着不包邮
                                "type" => $params['type'],
                            ]);
                        } else {
                            ShippingTempFree::create([
                                "province_id" => implode(',', $province_id),
                                "temp_id" => $temp_id,
                                // "city_id" => implode(',', $city_id),
                                "number" => $val['number'] ?? 0, //默认包邮单位为0 意味着不包邮
                                "price" => $val['price'] ?? 0, //默认包邮价格为0 意味着不包邮
                                "type" => $params['type'],
                            ]);
                        }
                    }
                }
                // 指定不送达
                if ($params['no_delivery'] == 1) {
                    // 开启不送达
                    if (!is_array($params['no_delivery_data'])) {
                        throw Error('请选择不送达的指定区域');
                    }
                    foreach ($params['no_delivery_data'] as $key => $val) {
                        $province_id = $val['province_id'] ?? [];
                        $city_id = $val['city_id'] ?? [];
                        if ($city_id && count($city_id)) {
                            ShippingTempNoDe::create([
                                "province_id" => implode(',', $province_id),
                                "temp_id" => $temp_id,
                                "city_id" => implode(',', $city_id),
                                "type" => $params['type'],
                            ]);
                        } else {

                            ShippingTempNoDe::create([
                                "province_id" => implode(',', $province_id),
                                "temp_id" => $temp_id,
                                //   // "city_id" => implode(',', $city_id),
                                "type" => $params['type'],
                            ]);
                        }
                    }
                }
            });
        } catch (\Exception $e) {
            throw new Error($e->getMessage());
        }
    }
}
